package com.zhengxiang.onlinexamination.service.impl;

import com.zhengxiang.onlinexamination.base.CacheConstants;
import com.zhengxiang.onlinexamination.base.Constants;
import com.zhengxiang.onlinexamination.base.UserConstants;
import com.zhengxiang.onlinexamination.component.AsyncFactory;
import com.zhengxiang.onlinexamination.component.AsyncManager;
import com.zhengxiang.onlinexamination.component.AuthenticationContextHolder;
import com.zhengxiang.onlinexamination.component.exception.user.ErrorCode;
import com.zhengxiang.onlinexamination.component.exception.user.UserErrorCode;
import com.zhengxiang.onlinexamination.component.exception.user.UserException;
import com.zhengxiang.onlinexamination.entity.LoginUser;
import com.zhengxiang.onlinexamination.entity.SysUser;
import com.zhengxiang.onlinexamination.service.SysUserService;
import com.zhengxiang.onlinexamination.service.SysLoginService;
import com.zhengxiang.onlinexamination.service.TokenService;
import com.zhengxiang.onlinexamination.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SysLoginServiceImpl implements SysLoginService {

    @Autowired
    private TokenService tokenService;


    @Resource
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserService userService;

    @Override
    public String login(String username, String password, String code, String uuid) {
        // 验证码开关
        if (false) {
            validateCaptcha(username, code, uuid);
        }
        // 用户验证
        Authentication authentication = null;
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        AuthenticationContextHolder.setContext(authenticationToken);
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        authentication = authenticationManager.authenticate(authenticationToken);

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    @Override
    public void validateCaptcha(String username, String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
            throw new UserException(UserErrorCode.VERIF_CODE_FAILURE, MessageUtils.message("user.jcaptcha.expire"));
        }
        if (!code.equalsIgnoreCase(captcha)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
            throw new UserException(UserErrorCode.VERIF_CODE_ERROR, MessageUtils.message("user.jcaptcha.expire"));
        }
    }

    @Override
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
